const { validationResult } = require('express-validator');
const {
    router,
    Result,
} = require('../connect');
const Busboy = require('busboy')
const path = require('path')
const fs = require('fs')

const boom = require('boom');
const { CODE_SUCCESS } = require('../utils/constant');

router.post('/upload', (req, res, next) => {
    const err = validationResult(req);
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        const busboy = Busboy({ headers: req.headers });

        let data = {
            filename: '', // 图片名字
            encoding: '', // 图片大小
            mimeType: '', // 图片格式
            imgUrl: '' // 图片地址
        }

        busboy.on('file', (name, file, info) => {
            const { filename, encoding, mimeType } = info;
            // 根据时间创建名字 - 防止重名
            const filePath = new Date().getTime() + path.extname(filename)

            const saveTo = path.join(__dirname, './uploads', filePath);

            // 保存数据
            data = { ...info, filename: filePath, originFilename: filename, imgUrl: saveTo }

            // 写入流
            file.pipe(fs.createWriteStream(saveTo));
        });

        busboy.on('finish', function () {
            res.json(new Result({
                code: CODE_SUCCESS,
                msg: '文件上传成功',
                data
            }))
        });

        return req.pipe(busboy);
    }

})

router.post('/gg', (req, res, next) => {
    res.json(new Result({
        code: CODE_SUCCESS,
        msg: '文件上传成功2334444',
        data: null
    }))
})

module.exports = router